<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import ip from '@/utils/baseURL.js'

const router = useRouter()

// 状态变量
const activeTab = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const news = ref([])

// 格式化时间数组为字符串
const formatTime = (timeArr) => {
    if (!timeArr || !Array.isArray(timeArr) || timeArr.length < 3) return '-'
    const [year, month, day] = timeArr
    // 补零处理
    const formatNumber = (n) => String(n).padStart(2, '0')
    return `${year}-${formatNumber(month)}-${formatNumber(day)}`
}

// 获取新闻数据
const fetchNews = async () => {
    try {
        const response = await axios.get(`${ip}/inter/journalism/getJournalism`)
        if (response.data.code === 200) {
            news.value = response.data.data
            total.value = response.data.data.length
        }
    } catch (error) {
        console.error('获取新闻列表失败:', error)
        news.value = []
    }
}

// 筛选新闻
const filteredNews = computed(() => {
    let result = news.value

    // 根据类型筛选
    if (activeTab.value !== 'all') {
        result = result.filter(item => item.label === activeTab.value)
    }

    // 按日期倒序排序（使用时间数组进行比较）
    return result.sort((a, b) => {
        const timeA = new Date(...a.time)
        const timeB = new Date(...b.time)
        return timeB - timeA
    })
})

// 计算筛选后的总数
const filteredTotal = computed(() => {
    return filteredNews.value.length
})

// 分页后的新闻列表
const paginatedNews = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return filteredNews.value.slice(start, end)
})

// 获取新闻类型标签样式
const getNewsTypeTag = (label) => {
    const tags = {
        '通知公告': 'warning',
        '新闻动态': 'danger',
        '成果交流': 'success'
    }
    return tags[label] || 'info'
}

// 获取新闻类型标签文本
const getNewsTypeLabel = (type) => {
    const labels = {
        notice: '通知文件',
        theory: '理论学习',
        meeting: '会议精神'
    }
    return labels[type] || '其他'
}

// 日期格式化
const formatDay = (timeArr) => {
    return timeArr[2] // 返回日期
}

const formatMonth = (timeArr) => {
    return `${timeArr[1]}月` // 返回月份
}

// 事件处理
const handleTabClick = () => {
    currentPage.value = 1 // 切换标签时重置到第一页
}

const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
}

const handleCurrentChange = (val) => {
    currentPage.value = val
}

const handleNewsClick = (news) => {
    router.push(`/user/news/detail?id=${news.id}`)
}

onMounted(() => {
    fetchNews()
})
</script>

<template>
    <div class="news-container">
        <div class="main-content">
            <!-- 页面标题 -->
            <div class="page-header">
                <h1>新闻中心</h1>
            </div>

            <!-- 新闻分类标签 -->
            <div class="news-tabs">
                <el-tabs v-model="activeTab" @tab-click="handleTabClick">
                    <el-tab-pane label="全部" name="all"></el-tab-pane>
                    <el-tab-pane label="新闻动态" name="新闻动态"></el-tab-pane>
                    <el-tab-pane label="通知公告" name="通知公告"></el-tab-pane>
                    <el-tab-pane label="成果交流" name="成果交流"></el-tab-pane>
                </el-tabs>
            </div>

            <!-- 新闻列表 -->
            <div class="news-list">
                <div v-for="item in paginatedNews" :key="item.id" class="news-item">
                    <div class="news-date">
                        <span class="day">{{ formatDay(item.time) }}</span>
                        <span class="month">{{ formatMonth(item.time) }}</span>
                    </div>
                    <div class="news-content">
                        <h3 class="news-title" @click="handleNewsClick(item)">
                            {{ item.title }}
                        </h3>
                        <div class="news-meta">
                            <el-tag :type="getNewsTypeTag(item.label)" size="small">
                                {{ item.label }}
                            </el-tag>
                            <span class="news-time">发布时间: {{ formatTime(item.time) }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 分页器 -->
            <div class="pagination-container">
                <el-pagination
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :total="filteredTotal"
                    :page-sizes="[10, 20, 30, 50]"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.news-container {
    .main-content {
        max-width: 1200px;
        margin: 0 auto;
        padding: 40px 20px;
    }

    .page-header {
        margin-bottom: 40px;
        text-align: center;

        h1 {
            font-size: 36px;
            color: #C00000;
            margin: 0;
            margin-bottom: 10px;
            position: relative;
            display: inline-block;
        }

        h2 {
            font-size: 24px;
            color: #333;
            margin: 0;
            position: relative;
            display: inline-block;
            padding-bottom: 15px;

            &::after {
                content: '';
                position: absolute;
                bottom: 0;
                left: 50%;
                transform: translateX(-50%);
                width: 60px;
                height: 4px;
                background-color: #C00000;
            }
        }
    }

    .news-tabs {
        margin-bottom: 30px;

        :deep(.el-tabs__nav-wrap::after) {
            background-color: #ebeef5;
        }

        :deep(.el-tabs__active-bar) {
            background-color: #C00000;
        }

        :deep(.el-tabs__item) {
            color: #666;
            font-size: 16px;

            &.is-active {
                color: #C00000;
            }

            &:hover {
                color: #C00000;
            }
        }
    }

    .news-list {
        .news-item {
            display: flex;
            gap: 20px;
            padding: 20px 0;
            border-bottom: 1px solid #ebeef5;
            transition: all 0.3s ease;

            &:hover {
                background-color: #f9f9f9;
                padding-left: 10px;
                padding-right: 10px;
                border-radius: 4px;
            }

            .news-date {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                min-width: 80px;
                padding: 10px;
                background-color: #f5f7fa;
                border-radius: 4px;

                .day {
                    font-size: 24px;
                    font-weight: bold;
                    color: #C00000;
                }

                .month {
                    font-size: 14px;
                    color: #666;
                }
            }

            .news-content {
                flex: 1;

                .news-title {
                    font-size: 18px;
                    color: #333;
                    margin: 0 0 10px 0;
                    font-weight: bold;
                    cursor: pointer;

                    &:hover {
                        color: #C00000;
                    }
                }

                .news-meta {
                    margin-bottom: 10px;
                    display: flex;
                    align-items: center;
                    gap: 15px;

                    .news-time {
                        color: #999;
                        font-size: 14px;
                    }
                }
            }
        }
    }

    .pagination-container {
        margin-top: 30px;
        display: flex;
        justify-content: center;
    }
}

// 响应式布局
@media (max-width: 768px) {
    .page-header {
        h1 {
            font-size: 28px !important;
        }
        
        h2 {
            font-size: 20px !important;
        }
    }

    .news-item {
        flex-direction: column !important;
        gap: 15px !important;

        .news-date {
            align-self: flex-start !important;
        }
    }
}
</style>